package store.dao;

import store.po.Goods;
import store.po.Sale;
import store.po.SaleItem;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class SaleItemDAO {
    public List<SaleItem> findSaleItems(int saleId) throws Exception{
        List<SaleItem> list=new ArrayList<>();
        Connection con= null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            Class.forName(DB.JDBC_DRIVER);
            con= DriverManager.getConnection(DB.JDBC_URL,DB.JDBC_USER,DB.JDBC_PASSWORD);
            ps=con.prepareStatement("SELECT si.count,g.* FROM t_sale_item as si inner join t_goods as g on si.goods_id=g.id where si.sale_id=?; ");
            ps.setInt(1,saleId);
            rs=ps.executeQuery();
            while (rs.next()){
                SaleItem si=new SaleItem();
                si.setCount(rs.getInt("count"));
                Goods g=new Goods();
                g.setId(rs.getInt("id"));
                g.setName(rs.getString("name"));
                g.setSpecs(rs.getString("specs"));
                g.setSn(rs.getString("sn"));
                g.setPrice(rs.getDouble("price"));
                g.setStock(rs.getInt("stock"));
                g.setCategoryId(rs.getInt("category_id"));
                si.setGoods(g);
                list.add(si);

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("数据库异常:"+e.getMessage());
        }finally {
            if(rs!=null) rs.close();
            if(ps!=null) ps.close();
            if(con!=null) con.close();
        }
        return list;
    }
}
